import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import type { ResponseData, RequestConfig } from '@/types/request'

// 创建加载实例
let loading: any
// 加载计数器
let loadingCount = 0

// 显示loading
const showLoading = () => {
  if (loadingCount === 0) {
    loading = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  loadingCount++
}

// 隐藏loading
const hideLoading = () => {
  loadingCount--
  if (loadingCount === 0) {
    loading?.close()
  }
}

class Request {
  // axios 实例
  private instance: AxiosInstance
  // 基础配置
  private baseConfig: AxiosRequestConfig = {
    baseURL: '',  // 使用空字符串
    timeout: 5000,
    headers: {
      'Content-Type': 'application/json'
    }
  }

  constructor(config?: AxiosRequestConfig) {
    // 创建axios实例
    this.instance = axios.create(Object.assign(this.baseConfig, config))

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log('Request Config:', config)
        
        // 是否需要显示loading
        if (config.loading) {
          showLoading()
        }
        
        // 是否需要token
        if (config.needToken) {
          const token = localStorage.getItem('token')
          if (token) {
            config.headers.Authorization = `Bearer ${token}`
          }
        }
        
        return config
      },
      (error) => {
        console.error('Request Error:', error)
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        console.log('Response:', response)
        
        // 隐藏loading
        if (response.config.loading) {
          hideLoading()
        }
        
        const res = response.data
        
        // 根据状态码处理
        if (res.code !== 200) {
          // 是否显示错误信息
          if (response.config.showError) {
            ElMessage.error(res.message || '请求失败')
          }
          return Promise.reject(res)
        }
        
        return res
      },
      (error) => {
        console.error('Response Error:', error)
        // 隐藏loading
        if (error.config?.loading) {
          hideLoading()
        }
        
        // 处理错误
        if (error.config?.showError) {
          ElMessage.error(error.message || '请求失败')
        }
        
        return Promise.reject(error)
      }
    )
  }

  // 通用请求方法
  public request<T = any>(config: RequestConfig & AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.request(config)
  }

  // GET请求
  public get<T = any>(url: string, config?: RequestConfig & AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.get(url, config)
  }

  // POST请求
  public post<T = any>(url: string, data?: any, config?: RequestConfig & AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.post(url, data, config)
  }

  // PUT请求
  public put<T = any>(url: string, data?: any, config?: RequestConfig & AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.put(url, data, config)
  }

  // DELETE请求
  public delete<T = any>(url: string, config?: RequestConfig & AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.delete(url, config)
  }
}

// 导出请求实例
export default new Request() 